﻿using GodSoft.Code;
using GodSoft.Common;
using GodSoft.Models;
using GodSoft.ViewModels;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;

namespace GodSoft.Controllers
{
    public class RoleController : BaseController
    {
        DataTable dt;

        GodSoftContext _context = new GodSoftContext();
        public ActionResult Index()
        {
            return View();
        }


        /// <summary>
        /// 设置角色权限
        /// </summary>
        /// <param name="ID">角色编号</param>
        /// <returns></returns>
        public ActionResult Set_Role_ActionShow(int ID)
        {
            if (_context.Roles.Find(ID).RoleName == "超级管理员")
            {
                return Content("不允许修改超级管理员权限!");
            
            }

            //父用户ID
            int currentUserID = Int32.Parse(Session["currentUserID"].ToString());
            //获取父用户所拥有的全部功能列表(Name,ID,ParentID)
            dt = PermissionAccess.GetActionInfoByUserID(currentUserID);
            if (dt.Rows.Count > 0)//如果父用户拥有权限信息,则生成权限树
            {
                ViewBag.RoleID = ID;
                return View();
            }
            else//父用户无权限信息
            {
               return Content("父用户无权限信息，无法为角色分配权限！");
            }
           
        }
        public ActionResult initTree(int RoleID)
        {
            Role role = _context.Roles.Include(a => a.ActionInfoes).Where(r => r.ID == RoleID).First();
            //获取该角色下的所有权限id
            List<int> roleActionInfoesID = new List<int>(role.ActionInfoes.Select(c => c.ID));

            //父用户ID
            int currentUserID = Int32.Parse(Session["currentUserID"].ToString());
            //获取父用户所拥有的全部功能列表(Name,ID,ParentID)
            dt = PermissionAccess.GetActionInfoByUserID(currentUserID);

            if (dt.Rows.Count > 0)//如果父用户拥有权限信息
            {
                int ParentID = Int32.Parse(dt.Rows[0][2].ToString());//第一行第三列
                string treedata = AddNode(dt, ParentID, 1, roleActionInfoesID);
                return Content(treedata);
            }
            else//父用户无权限信息
            {
                return Content("父用户无权限信息");
                
            }



        }

        /// <summary>  
        /// 无限递归，生成easyui tree可用的json数据 
        /// </summary>  
        /// <param name="ParentID">父id</param>  
        /// <param name="deep">开始深度，默认为1</param>  
        /// <returns></returns>  
        private string AddNode(DataTable dt, int ParentID, int deep, List<int> roleActionInfoesID)
        {
            string str = "";
            DataView dvTree = new DataView(dt);
            dvTree.RowFilter = "[ParentID]='" + ParentID + "'";//过滤出ParentId  

            int i = 0;
            int d = deep;
            foreach (DataRowView drv in dvTree)
            {

                if (i == 0)//如果是某一层的开始，需要“[”开始  
                {
                    if (d == 1)//如果深度为1,即第一层  
                        str = "[";
                    else//否则，为第二层或更深  
                        str = ",\"children\":[";
                }

                else
                    str = str + ",";



                str = str + "{";
                str = str + "\"id\":\"" + drv["ID"] + "\",";
                str = str + "\"text\":\"" + drv["ActionName"] + "\",";

                if (roleActionInfoesID.Contains(Convert.ToInt32(drv["ID"])))
                {
                    str = str + "\"checked\":true";
                }
                else
                {
                    str = str + "\"checked\":false";
                }

                str = str + AddNode(dt, Convert.ToInt32(drv["ID"]), deep + 1, roleActionInfoesID);//递归  

                str = str + "}";
                i = i + 1;

                if (dvTree.Count == i)//如果某一层到了末尾,需要"]"结束  
                    str = str + "]";

            }

            return str;
        }

        /// <summary>
        /// 更新角色权限
        /// </summary>
        /// <param name="RoleID">角色ID</param>
        /// <param name="ActionIDS">提交的权限ID序列</param>
        public ActionResult UpdateRoleActionInfoes(int RoleID, string selectedActionInfoIDS)
        {

            //截取传递过来的字符串的数字信息
            var idsStr = selectedActionInfoIDS.Split(',');

            List<int> selectedActionInfoesList = new List<int>();//现在角色的权限ID列表

            foreach (var ID in idsStr)
            {
                selectedActionInfoesList.Add(Convert.ToInt32(ID));
            }
            //要修改的角色信息
            Role roleToUpdate = _context.Roles.Include(i => i.ActionInfoes).Where(r => r.ID == RoleID).FirstOrDefault();
            //原来角色的权限ID列表
            var roleActionInfoes = new List<int>(roleToUpdate.ActionInfoes.Select(c => c.ID));

            //修改当前角色的权限信息
            roleToUpdate.ActionInfoes = new List<ActionInfo>();//清空原来的权限信息
            foreach (int id in selectedActionInfoesList)//设置为现在的权限信息
            {
                roleToUpdate.ActionInfoes.Add(_context.ActionInfoes.Find(id));
                _context.SaveChanges();

            }
            if (roleActionInfoes != null)//原来角色的权限ID列表 不为空
            {
                List<int> ListResult = new List<int>();
                ListResult = roleActionInfoes.Except(selectedActionInfoesList).ToList();//求差集(撤销的权限ID列表)
                if (ListResult != null)//需要撤销的权限ID列表不为空
                {
                    if (roleToUpdate.UserInfoes.Count <= 0)//角色未分配给用户,退出
                    {
                        return Content("OK");
                    }

                    UserInfo userinfo = roleToUpdate.UserInfoes.FirstOrDefault();//拥有该角色的用户信息
                    int userid = userinfo.ID;//拥有该角色的用户id
                    //修改子用户角色权限信息
                    //找到所有子用户 子用户对应权限 判断子用户权限范围内是否含有 应撤销的权限 删除之。

                    //获取全部用户ID，ParentID
                    dt = PermissionAccess.GetAllUserIDAndParentID();
                    return Content(UpdateChildrenUserRoleAction(dt, userid, ListResult));
                }
                else
                {
                    return Content("OK");

                }

            }
            else
            {
                return Content("OK");

            }



        }
        /// <summary>
        /// 递归删除子用户应该删除的权限
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="ParentID"></param>
        /// <param name="ListResult"></param>
        public string UpdateChildrenUserRoleAction(DataTable dt, int ParentID, List<int> ListResult)
        {
            try
            {
                DataView dvUser = new DataView(dt);
                dvUser.RowFilter = "[ParentID]='" + ParentID + "'";//过滤出ParentId  

                foreach (DataRowView drv in dvUser)
                {
                    int UserID = Convert.ToInt32(drv["ID"]);

                    List<int> UserActionIDs = new List<int>();
                    //获取用户所拥有的全部功能列表(Name,ID,ParentID)
                    DataTable UserActionDT = PermissionAccess.GetActionInfoByUserID(UserID);
                    foreach (DataRow Row in UserActionDT.Rows)
                    {

                        UserActionIDs.Add(Int32.Parse(Row["ID"].ToString()));
                    }
                    List<int> CutActionIDS = new List<int>();

                    CutActionIDS = UserActionIDs.Intersect(ListResult).ToList();//求交集

                    if (CutActionIDS.Count() > 0)//需要撤销子用户的权限
                    {
                        foreach (int id in CutActionIDS)
                        {
                            PermissionAccess.CutActionFromUserByUserID(UserID, id);//删除用户的权限
                        }

                    }

                    UpdateChildrenUserRoleAction(dt, UserID, ListResult);//递归删除子用户应该删除的权限信息
                }

            }
            catch
            {
                return "删除子用户权限出现错误，请您检查，或通知系统管理员!";
            }

            return "OK";

        }


        /// <summary>
        /// 创建子角色
        /// </summary>
        /// <param name="Role"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Regist(Role Role)
        {
            //获取当前登录用户ID
            int currentUserID = Int32.Parse(Session["currentUserID"].ToString());
            Role.CreateUserID = currentUserID;
            Role.SubTime = DateTime.Now;
            _context.Roles.Add(Role);
            _context.SaveChanges();
            return Content("OK");
        }

        public ActionResult GetAll()
        {
            int pageIndex = Request["page"] == null ? 1 : int.Parse(Request["page"]);
            int pageSize = Request["rows"] == null ? 10 : int.Parse(Request["rows"]);

            int currentUserID = Int32.Parse(Session["currentUserID"].ToString());
            //查看登录用户创建的子角色信息
            var temp = from i in _context.Roles
                       where i.CreateUserID == currentUserID
                       orderby i.ID
                       select new
                       {
                           i.ID,
                           i.RoleName,
                           CreateUserID = currentUserID,
                           i.DelFlag,
                           i.SubTime,
                           i.Describe
                       };
            var list = temp.Skip((pageIndex - 1) * pageSize).Take(pageSize);
            var result = new { total = temp.Count(), rows = list };
            return Json(result, JsonRequestBehavior.AllowGet);

        }
        /// <summary>
        /// 更新角色信息
        /// </summary>
        /// <param name="Role"></param>
        /// <returns></returns>
        public ActionResult UpdateInfo(Role Role)
        {

            _context.Roles.Attach(Role);
            _context.Entry<Role>(Role).State = EntityState.Modified;
            _context.SaveChanges();
            return Content("OK");
        }
        /// <summary>
        /// 删除角色
        /// </summary>
        /// <param name="deleteInfoID"></param>
        /// <returns></returns>
        public ActionResult DeleteInfo(string deleteInfoID)
        {
            if (string.IsNullOrEmpty(deleteInfoID))
            {
                return Content("请选择您要删除的数据!");
            }
            //截取传递过来的字符串的数字信息
            var idsStr = deleteInfoID.Split(',');

            List<int> deleteIDList = new List<int>();

            foreach (var ID in idsStr)
            {
                deleteIDList.Add(Convert.ToInt32(ID));
            }
            int result;
            result=DeleteManyInfoes(deleteIDList);
            if (result > 0)
            {
                return Content("OK");
            }
            else if (result == 0)
            {
                return Content("删除失败，请您检查!");
            }
            else
            {
                return Content("超级管理员不允许删除!");
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="DeleteIDList">删除的角色编号列表</param>
        /// <returns></returns>
        public int DeleteManyInfoes(List<int> DeleteIDList)
        {
            foreach (var id in DeleteIDList)
            {
                //获取角色信息
                Role Role = _context.Roles.Include(i => i.ActionInfoes).Include(i => i.UserInfoes).Where(f => f.ID == id).FirstOrDefault();
                
                if (Role.RoleName == "超级管理员")
                {
                    return -1;
                }


                if (Role.UserInfoes.Count() > 0) //该角色已分配给用户
                {
                    if (Role.ActionInfoes.Count() > 0)//如果角色拥有权限
                    {
                        //获取该角色下的所有用户ID
                        List<int> UsersID = new List<int>(Role.UserInfoes.Select(c => c.ID));
                        try
                        {
                            //获取全部用户ID，ParentID
                            dt = PermissionAccess.GetAllUserIDAndParentID();

                            //递归删除子用户权限信息
                            foreach (int UserID in UsersID)
                            {
                                DeleteUserFromRoleAndActions(UserID);//删除该用户的权限信息
                                //递归删除该用户和其子用户的权限信息
                                RecursionDelete(dt, id);

                            }

                            //最后删除该角色相关信息
                            Role.ActionInfoes = new List<ActionInfo>();
                            Role.UserInfoes = new List<UserInfo>();
                            _context.Roles.Remove(Role);//删除该角色
                            _context.SaveChanges();

                            return 1;//删除成功
                        }
                        catch
                        {
                            return 0;//删除异常

                        }
                    }
                    else//角色没有权限信息
                    {
                        //消除主键外键约束 
                        Role.UserInfoes = new List<UserInfo>();
                        _context.Roles.Remove(Role);//删除该角色
                        _context.SaveChanges();

                        return 1;//删除成功

                    }
                }
                else//该角色未分配给用户
                {
                    Role.ActionInfoes = new List<ActionInfo>();
                    _context.Roles.Remove(Role);//删除该角色
                    _context.SaveChanges();
                    return 1;//删除成功
                }
            }
            return 1;//删除成功

        }

        /// <summary>
        /// 递归删除
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="ParentID"></param>
        public void RecursionDelete(DataTable dt, int ParentID)
        {
            DataView dvUser = new DataView(dt);
            dvUser.RowFilter = "[ParentID]='" + ParentID + "'";//过滤出该用户的一级子用户

            foreach (DataRowView drv in dvUser)
            {
                int UserID = Convert.ToInt32(drv["ID"]);
                DeleteUserFromRoleAndActions(UserID);//删除子用户的权限信息
                RecursionDelete(dt, UserID);//递归删除

            }

        }
        /// <summary>
        /// 删除用户权限信息
        /// </summary>
        /// <param name="UserID">用户ID</param>
        public void DeleteUserFromRoleAndActions(int UserID)
        {
            UserInfo userInfo = _context.UserInfoes.Include(i => i.Roles).Where(f => f.ID == UserID).FirstOrDefault();

            if (userInfo.Roles.Count() > 0)//用户包含角色信息
            {
                int RoleID = userInfo.Roles.First().ID;//获取角色编号

                //userInfo.Roles = new List<Role>();//删除关联表(UserInfoRole)信息
                // _context.UserInfoes.Remove(userInfo);//删除用户信息

                Role role = _context.Roles.Include(i => i.ActionInfoes).Where(f => f.ID == RoleID).First();//得到角色拥有权限信息
                role.ActionInfoes = new List<ActionInfo>();//删除关联表(ActionInfoRole)信息（废除该用户权限但用户还拥有角色信息）
                // _context.Roles.Remove(role);//删除角色信息

                _context.SaveChanges();
            }
            else //用户不含角色信息
            {
                userInfo.Roles = null;
                _context.SaveChanges();//保存
            }


        }


    }
}
